<template>
  <div style="height: 750px">
    <el-row :gutter="20" class="mb10 row-style">
      <el-col :span="5" class="height-auto">
        <div class="div-style" style="padding: 18px 18px 18px 0px">
          <el-form ref="prescriptionFormRef" :model="prescriptionForm" :rules="prescriptionRules"
                   class="apply-form" label-width="100px">
            <el-form-item label="处方类型" prop="prescriptionType">
              <el-radio-group v-model="prescriptionForm.prescriptionType" :disabled="!isDisabled"
                              class="prescriptionType-radio"
                              @change="prescriptionTypeChange">
                <el-radio v-for="(dict, index) in dictDataMap['drug_classification']"
                          v-show="dict.dictLabel === '中草药'" :key="dict.dictValue"
                          :value="dict.dictValue">{{
                    dict.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="发药药房" prop="implementDept">
              <el-select v-model="prescriptionForm.implementDept"
                         placeholder="请输入发药药房" style="width: 240px">
                <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"
                           :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="汤药名" prop="decoctionName">
              <el-input v-model="prescriptionForm.decoctionName" :disabled="!isDisabled"
                        placeholder="请输入汤药名"
                        style="width: 240px"/>
            </el-form-item>
            <el-form-item label="处方备注" prop="remarks">
              <el-input v-model="prescriptionForm.remarks" :disabled="!isDisabled" :rows="4"
                        maxlength="100" placeholder="请输入处方备注信息"
                        show-word-limit style="width: 240px" type="textarea"/>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="2" class="height-auto">
        <div class="button-div mt10">
          <el-button class="mb10 ml10" plain type="primary" @click="getList">
            <template #icon>
              <i-ep-search/>
            </template>
            刷新
          </el-button>
          <el-button :disabled="isDisabled && !prescriptionForm.applyId" class="mb10 ml10" plain
                     style="margin-left: 12px;"
                     type="primary" @click="handleAdd">
            <template #icon>
              <i-ep-plus/>
            </template>
            处方新增F1
          </el-button>
          <el-button :disabled="!isDisabled" class="mb16 ml10" plain type="danger" @click="resetPrescription">
            <template #icon>
              <i-ep-refresh/>
            </template>
            重置
          </el-button>
          <el-button class="mb10 ml10" plain type="warning" @click="historyClick">
            <svg-icon class="mr5" icon-class="history"/>
            历史
          </el-button>
          <el-button class="mb10 ml10" color="#8888ff" plain @click="templateOpen">
            <svg-icon class="mr5" icon-class="template"/>
            模板
          </el-button>
          <el-badge :value="0" type="primary">
            <el-button class="mb10 ml10" color="#8888ff" plain @click="commonItemsClick">
              <template #icon>
                <i-ep-printer/>
              </template>
              常用项目
            </el-button>
          </el-badge>
          <el-button :disabled="!isDisabled" class="mb10 ml10" plain type="success" @click="submitForm">
            <svg-icon class="mr5" icon-class="save"/>
            处方保存
          </el-button>
          <!-- <div></div> -->
          <!-- <div></div> -->
        </div>
      </el-col>
      <el-col :span="17" style="height: 100%">
        <div class="div-style" style="padding: 10px;">
          <el-table :border="true" :data="prescriptionApplyList" :header-cell-style="$headerCellStyle"
                    :stripe="true"
                    highlight-current-row @row-click="rowClick">
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申请序号" prop="applyNo"
                             width="100"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="汤药名"
                             prop="decoctionName"
                             width="100"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方属性"
                             prop="prescAttr"
                             width="80">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['prescription_type']"
                               :value="scope.row.prescAttr"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="处方分类"
                             prop="itemClass"
                             width="70">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['bill_item_class_dict']"
                               :value="scope.row.itemClass"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="收费标志"
                             prop="chargeFlag"
                             width="135">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                               :value="scope.row.chargeFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="开单科室" prop="applyDeptName"/>
            <el-table-column :align="'center'" label="开单时间" prop="createTime" width="130"/>
            <el-table-column :align="'center'" label="发药药房" prop="implementDeptName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="发药标志"
                             prop="confirmFlag"
                             width="90">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['grant_flag']" :value="scope.row.confirmFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="发药执行人" prop="implementUserName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="发药时间"
                             prop="grantTime"
                             width="130">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.grantTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注信息"
                             prop="remarks"/>
            <el-table-column :align="'center'" label="确认退药人" prop="returnDrugUser"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="确认退药时间"
                             prop="returnDrugTime"
                             width="130">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.returnDrugTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="90"/>
            <el-table-column :align="'left'" class-name="small-padding fixed-width" fixed="right"
                             label="操作"
                             width="80">
              <template #default="scope">
                <el-tooltip class="item" content="打印" effect="dark" placement="top">
                  <el-button circle type="primary" @click="prescPrint(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip v-if="scope.row.chargeFlag === '1' && scope.row.orderStatus === '1'"
                            class="item" content="删除"
                            effect="dark"
                            placement="top">
                  <el-button circle type="danger" @click="handleDelete(scope.row)">
                    <template #icon>
                      <i-ep-delete/>
                    </template>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                      @pagination="getList"/>
        </div>
      </el-col>
    </el-row>
    <el-row class="bottom-row">
      <el-col :span="24" class="height-auto">
        <chinese-medicine ref="chineseMedicineRef" :apply-is-disabled="isDisabled" :org-id="userInfo.orgId"
                          @submit-ok="submitOk" @item-submit-ok="itemSubmitOk"/>
      </el-col>
    </el-row>
    <!-- 精麻毒类处方、诊断列表弹出框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="45%"
               @close="cancel">
      <el-divider content-position="left"><span class="divider-css">诊断信息</span></el-divider>
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="diagnosisList">
          <el-table ref="hisDiagnosisRef" :border="true" :data="hisDiagnosisList" :header-cell-style="$headerCellStyle"
                    :stripe="true" highlight-current-row style="margin-bottom: 28px"
                    @select="hisDiagnosisSelectionChange">
            <el-table-column :align="'center'" type="selection" width="40"/>
            <el-table-column :align="'center'" label="西/中医诊断" prop="type">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['chinese_western_type']" :value="scope.row.type"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="诊断类型" prop="diagnosisType" width="110px">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['diagnosis_type']"
                               :value="scope.row.diagnosisType"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊断名称" prop="icdName"
                             width="150px"/>
            <el-table-column :align="'center'" label="诊断编码" prop="icdCode"/>
            <el-table-column :align="'center'" label="效果" prop="effect">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['treatment_type']" :value="scope.row.effect"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="诊断医生" prop="diagnosisDoctorName"/>
          </el-table>
        </el-form-item>
        <template v-if="prescriptionForm.prescAttr === '3' || prescriptionForm.prescAttr === '4'
                    || prescriptionForm.prescAttr === '7'">
          <el-divider content-position="left"><span class="divider-css">人员信息</span></el-divider>
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="是否本人">
                <el-select v-model="dialogForm.agency" style="width: 100%" @change="agencyChange">
                  <el-option key="1" label="代办人" value="1"/>
                  <el-option key="2" label="本人" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人姓名' : '本人姓名'"
                            prop="agencyBy">
                <el-input v-model="dialogForm.agencyBy"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人年龄' : '本人年龄'"
                            prop="agencyAge">
                <el-input v-model="dialogForm.agencyAge"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="dialogForm.agency === '1' ? '代办人性别' : '本人性别'"
                            prop="agencySex">
                <el-select v-model="dialogForm.agencySex">
                  <el-option v-for="dict in dictDataMap['sys_user_sex']" :key="dict.dictValue"
                             :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="dialogForm.agency === '1' ? '代办人身份证' : '本人身份证'" prop="agencyNo">
            <el-input v-model="dialogForm.agencyNo"/>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dialogOk">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>

    <!-- 历史、常用项目、模板弹出框 -->
    <el-dialog v-model="historyOpen" :close-on-click-modal="false" :title="historyTitle" append-to-body width="90%"
               @close="historyCancel">
      <history v-if="historyType === 1" :org-id="userInfo.orgId" :patient-id="patientId"
               :refresh-key="historyKey" @apply-quote="historyApplyQuote"/>
      <template-quote v-else-if="historyType === 3" ref="templateQuoteRef" :query-params="templateParams"
                      :refresh-key="historyKey" @quote-ok-index="quoteOkIndex"/>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {
  delPrescriptionApply,
  getPrescriptionApply,
  refundApplication,
  selectPagePrescriptionApply
} from "@/api/patient/prescriptionApply.ts";
import {listHisDiagnosis} from "@/api/diagnosis/hisDiagnosis.ts";
import {useUserStoreHook} from "@/store/modules/user.ts";
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import ChineseMedicine from "./chineseMedicine.vue";
import templateQuote from "@/views/doctor/prescription/template/templateQuote.vue"
import {idNo} from "@/utils/myRules.ts"
import history from '@/views/doctor/prescription/history.vue';

const dictStore = useDictStoreHook();
const {proxy} = getCurrentInstance() as any;
const templateQuoteRef = ref()
const currentSelectDept = proxy.$currentSelectDept
// 患者门诊信息
const clinicInfo = ref<any>(proxy.$clinicInfo)

const formRef = ref();

const objectUrl = ref("")
const emits = defineEmits(["submitFormOk"])
// 左上方处方主信息form
const prescriptionFormRef = ref();
// 西药或中药：true 西药 ； false 中药
const westOrChinese = ref<boolean>(true)
// 药房list
const drugVsDeptList = ref<any>([])
const westernDrugList = ref<any>([])
const chineseDrugList = ref<any>([])
const title = ref<string>("信息选择")
// 历史、常用项目、模板弹出框 标题
const historyTitle = ref<string>("")
const open = ref<boolean>(false)
// 、模板弹出框 关闭打开状态
const historyOpen = ref<boolean>(false)
// 历史、常用项目、模板弹出框 内容状态 1：历史 2：常用项目 3：模板
const historyType = ref<number>(1)
const total = ref(0);
// 诊断列表
const ids = ref([""]);
const hisDiagnosisRef = ref()
// 诊断列表
const hisDiagnosisList = ref<any>([])
const historyKey = ref<number>(0)
// 中药明细组件
const chineseMedicineRef = ref()
// 处方主信息是否禁用
const isDisabled = ref<boolean>(false)
let dictDataMap = ref(dictStore.isTypeGetData('prescription_type', 'drug_classification', 'bill_item_class_dict',
  'charge_flag_dict', 'grant_flag', 'sys_user_sex', 'diagnosis_type', 'chinese_western_type'))
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const prescriptionApplyList = ref([]);
const props = defineProps({
  inoroutFlag: {
    type: String,
    default: ""
  },
  visitId: {
    type: String,
    default: ""
  },
  patientId: {
    type: String,
    default: ""
  }
});
const templateParams = ref<TemplateMasterType>({
  pageNum: 1,
  pageSize: 10,
  type: "1",
  authorityType: userInfo.customerType != '3' ? '' : "0",
  title: "",
  titleInput: "",
  deptId: userInfo.loginDeptId,
  orgId: userInfo.orgId,
  itemClass: "B"
})
const queryParams = ref<any>({
  orgId: userInfo.orgId,
  visitId: props.visitId,
  patientId: props.patientId,
  inoroutFlag: props.inoroutFlag,
  itemClass: 'B',
  orderStatus: '4'
});
// 左上方处方主信息form
const prescriptionForm = ref<any>({
  prescriptionType: '2',
  visitId: props.visitId,
  patientId: props.patientId,
  inoroutFlag: props.inoroutFlag,
  implementDept: "",
  prescAttr: "2",
  drugClass: "A",
  applyDept: userInfo.loginDeptId,
  applyUser: userInfo.userId,
  prescriptionItemBoList: [],
  orgId: userInfo.orgId,
  hisDiagnosisList: {},
  decoctionName: ""
})
const prescriptionRules = ref<any>({
  implementDept: [
    {
      required: true, message: "发药药房不能为空", trigger: "blur"
    }
  ],
  prescriptionType: [
    {
      required: true, message: "处方类型不能为空", trigger: "blur"
    }
  ],
  prescAttr: [
    {
      required: true, message: "处方属性不能为空", trigger: "change"
    }
  ],
  // decoctionName: [
  //     {
  //         required: true, message: "汤药名不能为空", trigger: "blur"
  //     }
  // ],
})
const dialogFormRef = ref()
const dialogForm = ref<any>({
  // 1代办  2本人
  agency: "1",
  agencyBy: '',
  agencyNo: '',
  agencyAge: '',
  agencySex: '',
  diagnosisList: ''
})
const dialogRules = ref<any>({
    diagnosisList: [
      {required: true, message: "请先开具诊断或者选择至少一条诊断后，再保存", trigger: "change"}
    ],
    agencyBy: [
      {required: true, message: "代办人不能为空", trigger: "blur"}
    ],
    agencyNo: [
      {required: true, validator: idNo, trigger: "blur"}
    ],
    agencyAge: [
      {required: true, message: "代办人年龄不能为空", trigger: "blur"}
    ],
    agencySex: [
      {required: true, message: "代办人性别不能为空", trigger: "blur"}
    ]
  }
)


getDrugVsDeptListFun()
getDiagnosisList()

// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: currentSelectDept,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("1,2", ","),
    storageTypeArray: proxy.$stringToArray("3,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("2", ","),
    // storageClass: '1'
    storageClassArray:  proxy.$stringToArray("1,3", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
    westernDrugList.value = res.data.filter((item: any) => {
      return item.storageClass !== "1"
    })
    chineseDrugList.value = res.data.filter((item: any) => {
      return item.storageClass !== "2"
    })
    prescriptionTypeChange()
  })
}

function prescriptionTypeChange() {
  // const drugClassificationArr: any = toRaw(dictDataMap.value['drug_classification'])
  let drugClassArray: any = []
  if (prescriptionForm.value.prescriptionType === "1") {
    // 西药
    drugVsDeptList.value = westernDrugList.value
    drugClassArray = drugVsDeptList.value[0].drugClass.split(",")
    westOrChinese.value = true
    prescriptionForm.value.drugClass = "A"
    const index = drugVsDeptList.value.findIndex((item: any) => {
      return "西药房" === item.storageName
    })
    if (index> -1) {
      prescriptionForm.value.implementDept = drugVsDeptList.value[index].storageCode
    } else {
      prescriptionForm.value.implementDept = drugVsDeptList.value[0].storageCode
    }
    prescriptionForm.value.prescAttr = "1"
    // drugClassificationArr.forEach((drugClassification: any) => {
    //     if (drugClassification.dictValue != "2") {
    //         drugClassArray.push(drugClassification.dictValue)
    //     }
    // })
  } else {
    // 中药
    drugVsDeptList.value = chineseDrugList.value
    westOrChinese.value = false
    prescriptionForm.value.drugClass = "B"
    const index = drugVsDeptList.value.findIndex((item: any) => {
      return "中药房" === item.storageName
    })
    if (index> -1) {
      prescriptionForm.value.implementDept = drugVsDeptList.value[index].storageCode
    } else {
      prescriptionForm.value.implementDept = drugVsDeptList.value[0].storageCode
    }
    prescriptionForm.value.prescAttr = "2"
    drugClassArray.push("2")
    nextTick(() => {
      chineseMedicineRef.value.setDrugClassArray(drugClassArray, prescriptionForm.value.implementDept)
    })
  }
}

function reset() {
}

/** 查询处方主表列表 */
function getList() {
  selectPagePrescriptionApply(queryParams.value).then((response: any) => {
    prescriptionApplyList.value = response.rows;
    total.value = response.total;
  });
}


// 组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown',
    handleKeydown);
});
// 组件卸载时移除事件监听以避免内存泄漏
onUnmounted(() => {
  window.removeEventListener('keydown',
    handleKeydown);
});

function handleKeydown(event) {
  if (event.keyCode == "112") {
    event.preventDefault();//阻止浏览器默认事件
    handleAdd()
  }
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构")
  }
  if (isDisabled.value && !prescriptionForm.value.applyId) {
    return ElMessage.error("处方信息已选择，不能再次新增。")
  }
  if (prescriptionForm.value.applyId) {
    ElMessageBox.confirm('点击新增处方操作，当前处方将会被重置，确定要进行删除操作吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      resetOk()
      addOk()
    }).catch(() => {
      ElMessage.info("操作终止")
    })
  } else {
    addOk()
  }
}

function addOk() {
  (prescriptionFormRef.value as any).validate(valid => {
    if (valid) {
      reset();
      isDisabled.value = true
      chineseMedicineRef.value.handleAddDrug()
    }
  })
}

// 处方主信息重置
function resetPrescription() {
  ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    resetOk()
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

// 历史按钮点击事件
function historyClick() {
  // 强制刷新弹出框内容
  historyKey.value = historyKey.value + 1
  historyTitle.value = "历史处方"
  historyOpen.value = true
  historyType.value = 1

}

// 模板按钮点击事件
function templateOpen() {
  // 强制刷新弹出框内容
  historyKey.value = historyKey.value + 1
  historyTitle.value = "模板"
  historyOpen.value = true
  historyType.value = 3
  templateParams.value.itemClass = prescriptionForm.value.prescriptionType === "1" ? "A" : "B"

}

// 常用项目按钮点击事件
function commonItemsClick() {
  historyTitle.value = "常用项目"
  historyOpen.value = true
  historyType.value = 2
}

function resetOk() {
  // isDisabled.value = false
  prescriptionForm.value.prescAttr = "1"
  prescriptionForm.value.remarks = ""
  prescriptionForm.value.visitId = props.visitId
  prescriptionForm.value.patientId = props.patientId
  prescriptionForm.value.inoroutFlag = props.inoroutFlag
  prescriptionForm.value.implementDept = ""
  prescriptionForm.value.prescAttr = "1"
  prescriptionForm.value.drugClass = prescriptionForm.value.prescriptionType === '1' ? "A" : "B"
  prescriptionForm.value.applyDept = userInfo.loginDeptId
  prescriptionForm.value.applyUser = userInfo.userId
  prescriptionForm.value.prescriptionItemBoList = []
  prescriptionForm.value.orgId = userInfo.orgId
  prescriptionForm.value.hisDiagnosisList = {}
  prescriptionForm.value.applyId = ""
  prescriptionForm.value.decoctionName = ""
  prescriptionTypeChange()
  if (prescriptionForm.value.prescriptionType === "1") {
    //prescriptionItemRef.value.emptyDrugList(false)
  } else {
    chineseMedicineRef.value.emptyDrugList(false)
  }
  // emits("submitFormOk");
}

/**
 * 诊断单选
 * @param selection
 */
function hisDiagnosisSelectionChange(selection: any) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    hisDiagnosisRef.value.toggleRowSelection(del_row, false);
  }
  ids.value = selection.map(item => item.id);
  const index = hisDiagnosisList.value.findIndex(item => {
    return item.id === ids.value[0]
  })
  if (index > -1) {
    dialogForm.value.diagnosisList = hisDiagnosisList.value[index]
  }

}

/**
 * 对明细进行校验
 */
function submitForm() {
  if (prescriptionForm.value.prescriptionType === "1") {
    //prescriptionItemRef.value.itemValidate()
  } else {
    if (prescriptionForm.value.decoctionName === "") {
      return ElMessage.error("汤药名称不能为空")
    }
    chineseMedicineRef.value.itemValidate()
  }
}

/**
 * 检验通过，弹出诊断选择狂
 * 校验通过后，由处方明细组件emits调用
 */
function itemSubmit() {
  open.value = true
  if (dialogForm.value.agency === "2") {
    dialogForm.value.agencyBy = clinicInfo.value.name
    dialogForm.value.agencyNo = clinicInfo.value.idNo
    dialogForm.value.agencyAge = clinicInfo.value.age
    dialogForm.value.agencySex = clinicInfo.value.sex
  }
  hisDiagnosisList.value.forEach((item: any) => {
    nextTick(() => {
      hisDiagnosisRef.value!.toggleRowSelection(item, false);
    })
  })
  const index = hisDiagnosisList.value.findIndex((item: any) => {
    return item.id === ids.value[0]
  })
  if (index > -1) {
    nextTick(() => {
      //让页面显示选中的数据
      hisDiagnosisRef.value.toggleRowSelection(hisDiagnosisList.value[index], true);
    })
  }
}

function agencyChange() {
  if (dialogForm.value.agency === "2") {
    dialogForm.value.agencyBy = clinicInfo.value.name
    dialogForm.value.agencyNo = clinicInfo.value.idNo
    dialogForm.value.agencyAge = clinicInfo.value.age + "岁" + clinicInfo.value.ageMonth + "月" + clinicInfo.value.ageDay + "天"
    dialogForm.value.agencySex = clinicInfo.value.sex
  } else {
    dialogForm.value.agencyBy = ""
    dialogForm.value.agencyNo = ""
    dialogForm.value.agencyAge = ""
    dialogForm.value.agencySex = ""
  }
}

/**
 * 是否确认保存
 */
function saveIsOk() {
  if (prescriptionForm.value.prescriptionType === "1") {
    //prescriptionItemRef.value.saveIsOk(prescriptionForm.value)
  } else {
    chineseMedicineRef.value.saveIsOk(prescriptionForm.value)
  }
}

function itemSubmitOk() {
  itemSubmit()
}

/**
 * 处方明细保存成功后事件
 */
function submitOk() {
  // getList()
  // resetOk()
  dialogForm.value.diagnosisList = []
  ids.value = []
  emits("submitFormOk")

}

/**
 * 右侧列表点击事件
 */
function rowClick(row: any) {
  getPrescriptionApply(row.applyId).then((res: resType) => {
    const data: any = res.data
    prescriptionForm.value = {
      prescriptionType: data.itemClass === "A" ? "1" : "2",
      visitId: data.visitId,
      patientId: data.patientId,
      inoroutFlag: data.inoroutFlag,
      implementDept: data.implementDept,
      prescAttr: data.prescAttr,
      drugClass: data.drugClass,
      applyDept: data.applyDept,
      applyUser: data.applyUser,
      remarks: data.remarks,
      orgId: data.orgId,
      applyId: data.applyId,
      diagnosis: data.diagnosis,
      drugInfoId: data.drugInfoId,
      icdName: data.icdName,
      icdCode: data.icdCode,
      diagnosisId: data.diagnosisId,
      decoctionName: data.decoctionName
    }
    ids.value = []
    ids.value.push(data.diagnosisId)
    const index = hisDiagnosisList.value.findIndex(item => {
      return item.id === ids.value[0]
    })
    if (index > -1) {
      dialogForm.value.diagnosisList = hisDiagnosisList.value[index]
    }
    isDisabled.value = data.orderStatus === '1'
    prescriptionTypeChange()
    applyRowClickFun(data)
  })
}


/**
 * 删除处方信息
 * @param row
 */
function handleDelete(row: any) {
  ElMessageBox.confirm('删除后数据将丢失，确定要进行删除操作吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delPrescriptionApply(row.applyId).then(() => {
      getList()
      resetOk()
      ElMessage.success("删除成功")
    })
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 关闭弹出框
 */
function cancel() {
  open.value = false
}

/**
 * 关闭历史、常用项目、模板弹出框
 */
function historyCancel() {
  // 清空模板明细信息
  if (historyType.value === 3) {
    nextTick(() => {
      templateQuoteRef.value.emptyPrescriptionItemList()
    })
  }
  historyOpen.value = false
}

/** 查询患者诊断表列表 */
function getDiagnosisList() {
  const form = {
    patientId: props.patientId,
    visitId: props.visitId
  }
  listHisDiagnosis(form).then((response: any) => {
    hisDiagnosisList.value = response.data;
  });
}

/**
 * 弹出框确认按钮
 */
function dialogOk() {
  (dialogFormRef.value as any).validate(valid => {
    if (valid) {
      prescriptionForm.value.agency = dialogForm.value.agency
      prescriptionForm.value.agencyAge = dialogForm.value.agencyAge
      prescriptionForm.value.agencyBy = dialogForm.value.agencyBy
      prescriptionForm.value.agencyNo = dialogForm.value.agencyNo
      prescriptionForm.value.agencySex = dialogForm.value.agencySex
      prescriptionForm.value.diagnosisList = dialogForm.value.diagnosisList
      saveIsOk()
    }
  })
}

/**
 * 历史处方引用事件
 */
function historyApplyQuote(obj: any) {
  const apply = obj.apply
  prescriptionForm.value = {
    prescriptionType: apply.itemClass === "A" ? "1" : "2",
    visitId: props.visitId,
    patientId: props.patientId,
    inoroutFlag: apply.inoroutFlag,
    prescAttr: apply.prescAttr,
    drugClass: apply.drugClass,
    orgId: apply.orgId,
    applyDept: userInfo.loginDeptId
  }
  isDisabled.value = true
  prescriptionTypeChange()
  if (prescriptionForm.value.prescriptionType === "1") {
    nextTick(() => {
      //prescriptionItemRef.value.applyRowClick(apply)
    })
  } else {
    nextTick(() => {
      chineseMedicineRef.value.applyRowClick(apply)
    })
  }
  historyCancel()
}

/**
 * 处方主记录点击事件、明细加载事件
 * @param data  prescription_apply 信息 主要要有applyId
 */
function applyRowClickFun(data: any) {
  if (prescriptionForm.value.prescriptionType === "1") {
    nextTick(() => {
      //prescriptionItemRef.value.applyRowClick(data)
    })
  } else {
    nextTick(() => {
      chineseMedicineRef.value.applyRowClick(data)
    })
  }
}


/** 申请退费 */
function refundApplicationFun(row, chargeFlag) {
  let message = "确认要进行申请退费？";
  if (chargeFlag === "2") {
    // 撤销退费
    message = "确认要进行撤销退费操作吗？";
  }
  ElMessageBox.confirm(message,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    refundApplication(row.applyId, chargeFlag).then((res: any) => {
      if (res.data) {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费成功。")
        } else if (chargeFlag === "3") {
          ElMessage.success("申请退费成功。")
        }
      } else {
        if (chargeFlag === "2") {
          ElMessage.success("撤销退费失败。")
        } else if (chargeFlag === "3") {
          ElMessage.error("申请退费失败。");
        }
      }
      getList()
    })
  })
}

/***********************************  模板引用  **********************************/
function quoteOkIndex(list: any) {
  if (prescriptionForm.value.prescriptionType === "1") {
    nextTick(() => {
      //prescriptionItemRef.value.templateQuote(list)
    })
  } else {
    nextTick(() => {
      chineseMedicineRef.value.templateQuote(list)
    })
  }
  isDisabled.value = true
  historyCancel()
}

/**
 * 处方打印
 * @param row
 */
function prescPrint(row: any) {
  let url = "/business/prescriptionApply/prescPrint";
  const formData = new FormData()
  formData.append("applyId", row.applyId)
  formData.append("orgId", row.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('处方打印失败')
    }
  })
}

defineExpose({
  getList
})
</script>

<style scoped>
.app-container {
  padding: 5px;
}

.row-style {
  height: 290px;
}

.bottom-row {
  height: calc(100% - 500px)
}

.height-auto {
  height: 100%;
}

.button-div {
  /** 将按钮容器设置为Flexbox布局。 **/
  display: flex;
  /** 将按钮容器的子元素垂直排列。 **/
  flex-direction: column;
  /** 将按钮容器的子元素在垂直方向上居中对齐。 **/
  /* align-items: center; */
  /** 将按钮容器的子元素在垂直方向上平均分布，实现等间距效果。 **/
  justify-content: space-between;
}

:deep(.prescriptionType-radio.el-radio-group) {
  display: inline-flex;
  align-items: center;
  flex-wrap: nowrap;
  font-size: 0;
}

:deep(.apply-form.el-form) {
  margin-left: -15px;
}

.el-table--fit {
  height: calc(100% - 24px) !important;
}
</style>
